<?php
/**
 * Created by PhpStorm.
 * User: admin
 * Date: 2020/1/11
 * Time: 15:41
 */
//生成图片验证码的controller php文件
namespace app\api\controller\v1;
use think\captcha\Captcha;
use think\Cookie;

class VerifyCode
{
    public function getCode(){//获取验证码图片

         //判断当前客户端是否有一个验证码标识 ,如果有则使用现有,如果没有则直接生成一个新的
         if(!isset($_COOKIE['verify_sign'])){
            //生成一个客户端验证码的标识码
            $sign = md5(time().mt_rand(1000,9999));
            cookie('verify_sign',$sign,5*60+8*60*60);
        }else{
            $sign = Cookie::get('verify_sign');
        }
        $captcha = new Captcha();
        return $captcha->entry($sign);
    }

    public function checkCode(){//验证图片验证码的正确性
        // echo '当前验证的标识sign为'.Cookie::get("verify_sign");
        $code = input("code");
        // echo '<br/>验证码为'.$code;

        $captcha = new Captcha();
        $sign = Cookie::get('verify_sign');

        if( $captcha->check($code, $sign) ){//判断是否通过了验证
            echo json_encode([
                'code'=>200,
                'msg'=>'图片验证码输入正确!'
            ],JSON_UNESCAPED_UNICODE);
        }else{
//             print_r([
//                 'code'=>0,
//                 'msg'=>'图片验证码输入错误!'
//             ]);
            echo json_encode([
                'code'=>0,
                'msg'=>'图片验证码输入错误!'
            ],JSON_UNESCAPED_UNICODE);
        }
    }
}